<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-tabs v-model="tabType" type="card" @tab-click="handleClick">
        <el-tab-pane label="物料申购" name="0"></el-tab-pane>
        <el-tab-pane label="教具申购" name="1"></el-tab-pane>
      </el-tabs>
      <div class="tab-body mb-10">
        <!--        // status 	整型 	必填 	1 	- 	状态 待审批 已审批（未下单 已下单 已入库） 驳回-->
        <!--        // 0待审核 1通过 2驳回 3未入库 4已入库-->
        <el-radio-group v-model="searchData.status" size="small" @change="changeFn
        ()">
          <el-radio-button :label="1">未下单({{ number ? number[1] : 0 }})</el-radio-button>
          <el-radio-button :label="3">已下单({{ number ? number[3] : 0 }})</el-radio-button>
        </el-radio-group>
      </div>
      <el-alert
          title="勾选对应的采购单进行导出"
          type="warning"
          class="mb-10"
          :closable="false">
      </el-alert>
      <div class="toplineBox mb-10">
        <div class="toplineBox-left">
          <el-input v-model="searchData.name" placeholder="名称" size="small" class="w-140 mr-10"></el-input>
          <!--          <el-input v-model="searchData.name" placeholder="金额" size="small" class="w-80 mr-10"></el-input>-->
          <el-input v-model="searchData.user_name" placeholder="申请人" size="small" class="w-80 mr-10"></el-input>
          <!--          <el-select placeholder="分类" size="small"-->
          <!--                     class="w-140 mr-10" v-model="searchData.status">-->
          <!--            <el-option :label="item.name" :value="item.id" v-for="(item, index) in optionsList"-->
          <!--                       :key="index"></el-option>-->
          <!--          </el-select>-->
          <el-date-picker
              v-model="addtime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="mr-10">
          </el-date-picker>
          <el-button type="primary" size="small" @click="searchFn(1)"><i class="el-icon-search"></i>搜索</el-button>
          <el-button size="small" @click="searchFn(2)"><i class="el-icon-refresh"></i>重置</el-button>
          <el-button @click="excelVisible=true" size="small" :disabled="applyBookBoxNumber.length?false:true">
            导出{{ searchData.status == 1 ? '未' : '已' }}下单{{ tabType == 1 ? '教具' : '物料' }}
          </el-button>
        </div>
        <p class="numberline toplineBox-right">总{{ page.total }}条</p>
      </div>
      <div class="applyBox" v-if="searchData.status==1">
        <span class="titlebook">请勾选下单{{ tabType == 1 ? '教具' : '物料' }}：</span><span class="applycart"
                                                                                   @click="showOrderList"><i
          class="iconfont icontushu"></i><span>共{{ applyBookBoxNumber.length }}件,点击查看</span></span>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <!--              @selection-change="handleSelectionChange"-->
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStyle.tableStripe"
              :border="tableStyle.tableBorder"
              tooltip-effect="dark"
              header-cell-class-name="table-text-c"
              style="width: 100%"
              @cell-click="cellClick"
              @select-all="selectAll"
              @row-click="rowClick"
              @select="selectFnBox">
            <el-table-column
                type="selection"
                width="50"
                align="center"
                :key="10">
            </el-table-column>
            <el-table-column
                prop="name"
                :label="Number(searchData.type)==0?'物料名称':'教具名称'"
                align="center"
                :key="1">
            </el-table-column>
            <el-table-column
                prop="need_number"
                label="数量"
                align="center"
                width="60"
                :key="2">
              <template slot-scope="scope">
                <el-link v-if="searchData.status == 1" @click="editDetailFn(scope.row, 'need_number')">
                  {{ scope.row.need_number }}
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.need_number }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                label="单价"
                align="center"
                width="90"
                :key="3">
              <template slot-scope="scope">
                <el-link type="danger" v-if="searchData.status == 1" @click="editDetailFn(scope.row, 'price')">
                  {{ scope.row.price }}
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.price }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="finance_source"
                label="资金来源"
                align="center"
                :key="55">
            </el-table-column>
            <el-table-column
                prop="create_time"
                label="申请时间"
                align="center"
                :key="6">
            </el-table-column>
            <el-table-column
                prop="pay_time"
                label="下单时间"
                align="center"
                v-if="searchData.status==3"
                :key="11">
            </el-table-column>
            <el-table-column
                prop="actual_number"
                label="实际下单数"
                width="94"
                align="center"
                v-if="searchData.status==3"
                :key="12">
            </el-table-column>
            <el-table-column
                prop="expect_time"
                label="期望交付日期"
                align="center"
                :key="4">
            </el-table-column>
            <el-table-column
                label="申请人"
                align="center"
                :key="5">
              <template slot-scope="scope">
                {{ scope.row.user ? scope.row.user.realname : '--' }}
              </template>
            </el-table-column>
            <el-table-column
                prop="url"
                label="采购网址"
                align="center"
                show-overflow-tooltip
                :key="7">
              <template slot-scope="scope">
                <el-link type="danger" v-if="searchData.status == 1" @click="editDetailFn(scope.row, 'url')">
                  <span style="width: 100px;overflow: hidden;display: block;">{{ scope.row.url }}</span>
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.url }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="remark"
                label="补充说明"
                align="center"
                show-overflow-tooltip
                :key="8">
            </el-table-column>
            <el-table-column
                label="照片"
                align="center"
                width="80"
                :key="9">
              <template slot-scope="scope">
                <ImagePreview :src="scope.row.pic" width="40px" height="40px"></ImagePreview>
              </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                align="center"
                width="90"
                :key="11">
              <template slot-scope="scope">
                <!--                0待审核1通过2驳回3完成-->
                <el-popover
                    placement="left-start"
                    title="下单详情"
                    width="220"
                    trigger="hover"
                    v-if="searchData.status==3">
                  <div class="tableline">
                    <p class="list">
                      <span>下单时间：<i
                          style="color: green">{{
                          scope.row.pay_time
                        }}</i></span>
                    </p>
                  </div>
                  <span slot="reference" class="tablelineBtn">{{ searchData.status == 1 ? '未下单' : '已下单' }}</span>
                </el-popover>
                <span class="tablelineBtn" v-else>{{ searchData.status == 1 ? '未下单' : '已下单' }}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="90">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" plain @click="handleDetel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <addOrder :visible.sync="orderVisible" :applyBookBox="applyBookBox" :applyBookBoxNumber="applyBookBoxNumber"
              @clearList="clearList" orderType="1"></addOrder>
    <el-dialog
        title="采购网址"
        :visible.sync="urlVisible"
        width="30%">
      <span>{{ urlPath }}</span>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="urlVisible = false, urlPath = ''" size="mini">确 定</el-button>
  </span>
    </el-dialog>
    <purchaseExcel :applyBookBox="applyBookBox" :orderType="searchData.status"
                   :visible.sync="excelVisible"></purchaseExcel>
    <editDetail :detailOption="detailOption" :visible.sync="detailEditVisible" @InitFn="InitFn"
                :detailType="detailType"></editDetail>
  </div>
</template>

<script>
import {pagination, tableoption} from '@/utils/util.js'
import addOrder from "./addOrder";
import purchaseExcel from "@/components/iframe-Excel-Out/purchaseExcel";
import editDetail from "./components/editDetail";
import {purchaseMyDelete} from '@/api/admin/purchase'

export default {
  components: {
    addOrder,
    purchaseExcel,
    editDetail
  },
  data() {
    return {
      detailEditVisible: false,
      detailOption: null,
      excelVisible: false,
      urlVisible: false,
      urlPath: '',
      orderVisible: false,
      radioStatus: 'all',
      handleSelection: [],
      arryList: [], // 页面数据列表
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      number: null,
      searchData: {
        name: '',
        user_name: '',
        start_time: '',
        end_time: '',
        status: '1', // 0待审核 1通过 2驳回 3未入库 4已入库
        type: '0', // 0 物料 1 教具
        p: 1
      },
      tabType: '0',
      value: '1',
      addtime: '',
      statusList: {
        0: '待审批',
        1: '未下单',
        2: '驳回申请',
        3: '未入库',
        4: '已入库'
      },
      multipleSelection: [],
      applyBookBox: {},
      applyBookBoxNumber: [],
      detailType: ''
    }
  },
  created() {
    this.InitFn()
  },
  methods: {
    editDetailFn(item, type) {
      this.detailType = type
      this.detailOption = JSON.parse(JSON.stringify(item))
      this.detailEditVisible = true
    },
    handleSelectionChange(val) {
      console.log('勾选内容', val)
      this.multipleSelection = val
    },
    handleClick(option) {
      console.log(option.name, this.searchData.type)
      if (Number(option.name) !== Number(this.searchData.type)) {
        this.searchData.type = option.name
        this.InitFn()
      }
    },
    searchFn(option) {
      this.page.pageindex = 1
      if (option === 1) {
        if (this.addtime) {
          this.searchData.start_time = this.addtime[0];
          this.searchData.end_time = this.addtime[1];
        } else {
          this.searchData.start_time = '';
          this.searchData.end_time = '';
        }
      } else {
        this.searchData.name = '';
        this.searchData.user_name = '';
        this.searchData.start_time = '';
        this.searchData.end_time = '';
      }
      this.applyBookBox = {}
      this.applyBookBoxNumber = []
      this.arryList = []
      console.log('收到搜索数据：', option);
      this.InitFn()
    },
    // 初始化
    InitFn() {
      // type 2 审核人员
      // examine_type 	整型 	必填 	1 	- 	状态0待审核1已审核
      // type 	整型 	必填 	1 	- 	类型0物料1教具
      this.searchData.p = this.page.pageindex
      let dataOption = this.getJson(this.searchData)
      let that = this
      // if(this.searchData.examine_type === 'all'){
      //   delete dataOption['examine_type']
      // }
      this.$fetch(this.api.purchase.list, dataOption).then((response) => {
        if (response.code === 0) {
          for (let item of response.list.data) {
            item.create_time = item.create_time.split(' ')[0]
          }
          this.arryList = JSON.parse(JSON.stringify(response.list.data))
          this.page.total = response.list.total
          this.number = response.number
          that.$nextTick(function () {
            that.checked() // 每次更新了数据，触发这个函数即可。
          })
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    examinBtn(type, id) {
      let that = this;
      if (type === 1) {
        this.$confirm('确认通过申购审批, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.subimitExamin(type, id)
        }).catch(() => {

        });
      } else {
        this.$prompt('输入申购审批驳回说明', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          // value
          that.subimitExamin(type, id, value)
        }).catch(() => {

        });
      }
    },
    changeFn() {
      this.applyBookBox = {}
      this.applyBookBoxNumber = []
      this.arryList = []
      this.searchData.p = 1
      this.InitFn()
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    // 搜索组件
    subimitExamin(type, id, value) {
      let n = this;
      let option = {id: id, type: type}
      if (type === 2) {
        option.content = value;
      }
      this.$post(this.api.purchase.examineBtn, option).then((response) => {
        if (response.code === 0) {
          n.InitFn()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 点击全选
    selectAll(val) {
      // 全选所有跟空值，即使页面已经选择2项
      console.log('点击全选', val)
      console.log(val) // 所有选中值
      let applyBookBox = this.applyBookBox
      if (val.length !== 0) {
        // this.handleSelection = val
        for (let i = 0; i < val.length; i++) {
          if (!applyBookBox[val[i].id]) {
            // 不存在图书
            applyBookBox[val[i].id] = val[i]
          }
        }
      } else {
        // 清除所有 arryList
        for (let i = 0; i < this.arryList.length; i++) {
          if (this.applyBookBox[this.arryList[i].id]) {
            // 存在图书删除
            delete applyBookBox[this.arryList[i].id]
          }
        }
      }
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      console.log('最后的数据：', this.applyBookBox, this.applyBookBoxNumber)
    },
    // 点击单选
    selectFnBox(val) {
      // 选择的是当前所有的选中，还需要比对未选中项 applyBookBoxInit
      console.log('本页面的列表数据', this.applyBookBoxInit)
      console.log('点击单选', val)
      let applyBookBox = this.getJson(this.applyBookBox)
      if (val.length !== 0) {
        // 有选项 对本页面的选项进行比对
        let valBox = {}
        for (let i = 0; i < val.length; i++) {
          valBox[val[i].id] = val[i]
        }
        for (let item of this.arryList) {
          if (valBox[item.id]) {
            // 存在图书删除
            applyBookBox[item.id] = item
          } else {
            delete applyBookBox[item.id]
          }
        }
      } else {
        // 清除所有 arryList本页面的数据
        for (let item of this.arryList) {
          delete applyBookBox[item.id]
        }
      }
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      console.log('最后的数据：', this.applyBookBox, this.applyBookBoxNumber)
    },
    showOrderList() {
      // applyBookBox: {},
      // applyBookBoxNumber: []
      if (JSON.stringify(this.applyBookBox) === '{}') {
        this.$message.error('请选择需要下单的物件')
        return
      }
      this.orderVisible = true;
    },
    clearList(option) {
      if (option.type === 'clear') {
        this.applyBookBox = {};
        this.applyBookBoxNumber = [];
        this.checked()
      } else if (option.type === 'delete') {
        this.applyBookBoxNumber.splice(this.applyBookBoxNumber.indexOf(option.index), 1)
        delete this.applyBookBox[option.index]
        this.checked()
      } else if (option.type === 'pay') {
        this.applyBookBox = {}
        this.applyBookBoxNumber = []
        this.InitFn()
      }
    },
    checked() {
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          this.$refs.multipleTable.toggleRowSelection(this.arryList[i], true)
        } else {
          this.$refs.multipleTable.toggleRowSelection(this.arryList[i], false)
        }
      }
    },
    rowClick(row, column, event) {
      console.log('行：', row, column, event, this.applyBookBox)
      if (column.label !== '采购网址' || column.label !== '数量' || column.label !== '单价'|| column.label !== '操作') {
        if (!this.applyBookBox[row.id]) {
          this.applyBookBox[row.id] = JSON.parse(JSON.stringify(row))
        } else {
          delete this.applyBookBox[row.id]
        }
        // if (!this.applyBookBox[row.id]) {
        //   this.applyBookBox[row.id] = row
        // } else {
        //   delete this.applyBookBox[row.id]
        // }
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
        let that = this
        this.$nextTick(function () {
          that.checked() // 每次更新了数据，触发这个函数即可。
        })
      }
    },
    cellClick(row, column, cell, event) {
      // if (column.label === "采购网址") {
      //   this.urlPath = row.url
      //   this.urlVisible = true
      // }
    },
    handleDetel(row) {
      this.$confirm(`确认删除【${row.name}】该采购单, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(row)
      }).catch(() => {
      })
    },
    detelRespon(row) {
      purchaseMyDelete({id: row.id}).then(res => {
        if (!res.code) {
          this.InitFn()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
  },
  mounted() {
  },
  // 缓存机制 end
}
</script>

<style scoped>

.wx-user-box-line img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 5px;
}

.wx-user-box-line {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-wx {
  cursor: pointer;
  padding: 5px;
}

.btn-wx:hover {
  color: #1b8de5;
  text-decoration: underline;
}

.delet-wx {
  color: red;
  cursor: pointer;
}

.delet-wx:hover {
  text-decoration: underline;
}

.tab-body {
  display: flex;
  align-items: center;
}

.tab-box {
  flex: 1;
}

.tab-box-list {
  display: flex;
  align-items: center;
}

.examinBtn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: red;
}

.examinBtn i {
  font-style: normal;
  color: #1b8de5;
  cursor: pointer;
  font-size: 12px;
}

.tableline .list i {
  font-style: normal;
}

.el-icon-edit-outline.priceLine {
  color: #0aa0ff;
  cursor: pointer;
}
</style>
